//
//  DesPlaceViewController.m
//  HappyTrip
//
//  Created by yuxuesong on 15-3-26.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DesPlaceViewController.h"
#import "DestinationPlaceViewController.h"
#import "DesDetailPlaceTableViewCell.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"

#define TABLEREUSE @"placeTabelViewReuse"

@interface DesPlaceViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)UITableView *placeTableView;
@property (nonatomic, retain)NSMutableArray *photoArr;
@property (nonatomic, retain)MBProgressHUD *progressHUD;

@end

@implementation DesPlaceViewController

- (void)dealloc
{
    [_placeTableView release];
    [_photoArr release];
    [_progressHUD release];
    [_sendPlaceId release];
    [_sendPlaceType release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    
    self.photoArr = [NSMutableArray array];
    [self handlePhotoData:0];
    [self setupView];
    
}

- (void)setupView
{
    self.title = @"更多景点";
    self.placeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT + 49) style:UITableViewStylePlain];
    self.placeTableView.delegate = self;
    self.placeTableView.dataSource = self;
    self.placeTableView.separatorStyle = NO;
    self.placeTableView.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [self.view addSubview:self.placeTableView];
    [_placeTableView release];
    
    [self.placeTableView registerClass:[DesDetailPlaceTableViewCell class] forCellReuseIdentifier:TABLEREUSE];
    
    self.progressHUD = [[MBProgressHUD alloc] initWithView:self.placeTableView];
    _progressHUD.labelText = @"请稍等...";
    _progressHUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_progressHUD];
    [_progressHUD release];
    [_progressHUD show:YES];
    
    //刷新加载
    [self.placeTableView addLegendHeaderWithRefreshingBlock:^{
        [self.placeTableView.header endRefreshing];
    }];
    [self.placeTableView addLegendFooterWithRefreshingBlock:^{
        static NSInteger i = 1;
        [self handlePhotoData:i++ * 20];
    }];
}

#pragma mark - tableView 协议方法们
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.photoArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DesDetailPlaceTableViewCell *placeCell = [tableView dequeueReusableCellWithIdentifier:TABLEREUSE];
    placeCell.selectionStyle = UITableViewCellSelectionStyleNone;
    placeCell.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    placeCell.placeDetailObject = [self.photoArr objectAtIndex:indexPath.row];
    return placeCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (self.view.frame.size.height + 49) / 4;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DestinationPlaceViewController *placeViewController = [[DestinationPlaceViewController alloc] init];
    DestinationDetailObject *detailObj = [self.photoArr objectAtIndex:indexPath.row];
    placeViewController.placeSendID = detailObj.idNumber;
    placeViewController.placeSendType = detailObj.typeNumber;
    [self.navigationController pushViewController:placeViewController animated:YES];
    [placeViewController release];
}

#pragma mark - 精选图片 数据加载
- (void)handlePhotoData:(NSInteger)startNumber
{
    NSString *urlStr =[NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/pois/sights/?sort=default&start=%ld&latitude=38.883890&longitude=121.545445", self.sendPlaceType, self.sendPlaceId, startNumber];
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTripCountrySelectPhotoPage", docPath, [urlStr hash]];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        NSMutableArray *photoArr = [NSMutableArray array];
        photoArr = [responseObject objectForKey:@"items"];
       
        for (NSMutableDictionary *photoDic in photoArr) {
            DestinationDetailObject *detailModel = [[DestinationDetailObject alloc] initWithDic:photoDic];
            [self.photoArr addObject:detailModel];
            [detailModel release];
        }
        [self.placeTableView reloadData];
        [_progressHUD removeFromSuperview];
        [self.placeTableView.header endRefreshing];
        [_placeTableView.footer endRefreshing];
        if (photoArr.count == 0){
            [self.placeTableView removeFooter];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        self.photoArr = [NSMutableArray array];
        NSMutableArray *photoArr = [NSMutableArray array];
        photoArr = [resultID objectForKey:@"items"];
        for (NSMutableDictionary *photoDic in photoArr) {
            DestinationDetailObject *detailModel = [[DestinationDetailObject alloc] initWithDic:photoDic];
            [self.photoArr addObject:detailModel];
            [detailModel release];
        }
        static NSInteger i = 1;
        if (1 == i) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力,请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
        }
        i++;
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
